package com.lzh.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.admin.mapper.AdUserMapper;
import com.lzh.admin.entity.AdUser;
import com.lzh.admin.service.AdUserService;
import com.lzh.common.utils.AppJwtUtil;
import com.lzh.common.utils.Md5Util;
import com.lzh.common.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author lzh
 * @since 2021-06-23
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private AdUserMapper adUserMapper;
    @Override
    public boolean saveUser(AdUser adUser) {
        //加盐
        String salt = RandomUtil.random(10);
        adUser.setSalt(salt);
        String pwd = Md5Util.toMD5(adUser.getPassword(), salt);
        adUser.setPassword(pwd);
        int insert = adUserMapper.insert(adUser);
        if (insert != 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Map<String, Object> login(AdUser adUser) {
        //根据用户名获取用户信息
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",adUser.getName());
        AdUser user = adUserMapper.selectOne(queryWrapper);
        if (user == null) {
           return null;
        }
        //获取盐值
        String salt = user.getSalt();
        //将用户输入的密码进行加密
        String pwd = Md5Util.toMD5(adUser.getPassword(),salt);
        if (!pwd.equals(user.getPassword())) {
            return null;
        }
        //登录成功->颁发令牌
        //user->map
        Map<String,Object> userInfo = new HashMap<>();
        String token = AppJwtUtil.createToken(user.getId().longValue());
        userInfo.put("token",token);
        user.setPassword("****");
        user.setSalt("");
        userInfo.put("user",user);
        return userInfo;
    }
}
